package com.zfb.videoscript.core

import android.content.Context
import android.util.Log
import androidx.room.*
import java.text.SimpleDateFormat
import java.util.*

@Entity(tableName = "operation_logs")
data class OperationLog(
    @PrimaryKey(autoGenerate = true) val id: Int = 0,
    val operation: String,
    val details: String,
    val timestamp: Long = System.currentTimeMillis()
)

@Dao
interface OperationLogDao {
    @Query("SELECT * FROM operation_logs ORDER BY timestamp DESC")
    suspend fun getAllLogs(): List<OperationLog>
    
    @Insert
    suspend fun insertLog(log: OperationLog)
    
    @Query("DELETE FROM operation_logs WHERE timestamp < :timestamp")
    suspend fun deleteOldLogs(timestamp: Long)
}

@Database(entities = [OperationLog::class], version = 1)
abstract class LogDatabase : RoomDatabase() {
    abstract fun operationLogDao(): OperationLogDao
    
    companion object {
        @Volatile
        private var INSTANCE: LogDatabase? = null
        
        fun getDatabase(context: Context): LogDatabase {
            return INSTANCE ?: synchronized(this) {
                val instance = Room.databaseBuilder(
                    context.applicationContext,
                    LogDatabase::class.java,
                    "operation_log_database"
                ).build()
                INSTANCE = instance
                instance
            }
        }
    }
}

class LogManager(context: Context) {
    private val logDao = LogDatabase.getDatabase(context).operationLogDao()
    private val dateFormat = SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.getDefault())
    
    suspend fun logOperation(operation: String, details: String = "") {
        try {
            val log = OperationLog(operation = operation, details = details)
            logDao.insertLog(log)
            // 同时输出到Logcat
            Log.i("操作日志", "[$operation] $details")
            
            // 清理30天前的日志
            val thirtyDaysAgo = System.currentTimeMillis() - (30 * 24 * 60 * 60 * 1000L)
            logDao.deleteOldLogs(thirtyDaysAgo)
        } catch (e: Exception) {
            Log.e("LogManager", "记录日志失败", e)
        }
    }
    
    suspend fun getAllLogs(): List<String> {
        return try {
            logDao.getAllLogs().map { log ->
                val date = dateFormat.format(Date(log.timestamp))
                "[$date] ${log.operation}: ${log.details}"
            }
        } catch (e: Exception) {
            Log.e("LogManager", "获取日志失败", e)
            emptyList()
        }
    }
} 